"use client"

import { useState, useEffect } from "react"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import {
  Label
} from "@/components/ui/label"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import {
  Users,
  Plus,
  Edit,
  Trash2,
  User as UserIcon,
  Mail,
  Phone,
  Building,
  Calendar,
  Shield,
  MoreHorizontal,
  Crown,
  Star,
  AlertCircle,
  CheckCircle
} from "lucide-react"

interface TeamMember {
  id: string
  projectId: string
  name: string
  email: string
  phone: string
  department: string
  position: string
  role: string
  joinDate: string
  leaveDate: string
  status: string
  responsibilities: string
  skills: string[]
  avatar: string
  createdBy: string
  createdAt: string
  updatedAt: string
}

interface TeamManagementProps {
  projectId: string
  projectName: string
}

export function TeamManagement({ projectId, projectName }: TeamManagementProps) {
  const [teamMembers, setTeamMembers] = useState<TeamMember[]>([])
  const [loading, setLoading] = useState(true)
  const [editingMember, setEditingMember] = useState<TeamMember | null>(null)
  const [dialogOpen, setDialogOpen] = useState(false)

  useEffect(() => {
    fetchTeamMembers()
  }, [projectId])

  const fetchTeamMembers = async () => {
    try {
      setLoading(true)
      const response = await fetch(`/api/projects/${projectId}/team`)
      if (response.ok) {
        const data = await response.json()
        // 如果返回的是对象，提取teamMembers属性；如果是数组，直接使用
        const teamMembersArray = Array.isArray(data) ? data : (data.teamMembers || [])
        setTeamMembers(teamMembersArray)
      }
    } catch (error) {
      console.error('Error fetching team members:', error)
      // 设置一些默认的示例数据
      setTeamMembers([])
    } finally {
      setLoading(false)
    }
  }

  const getStatusColor = (status: string) => {
    const statusColors: Record<string, string> = {
      'ACTIVE': 'bg-green-100 text-green-800',
      'INACTIVE': 'bg-gray-100 text-gray-800',
      'PENDING': 'bg-yellow-100 text-yellow-800',
      'LEFT': 'bg-red-100 text-red-800'
    }
    return statusColors[status] || 'bg-gray-100 text-gray-800'
  }

  const getRoleColor = (role: string) => {
    const roleColors: Record<string, string> = {
      'LEADER': 'bg-purple-100 text-purple-800',
      'MANAGER': 'bg-blue-100 text-blue-800',
      'MEMBER': 'bg-gray-100 text-gray-800',
      'CONTRIBUTOR': 'bg-green-100 text-green-800'
    }
    return roleColors[role] || 'bg-gray-100 text-gray-800'
  }

  const getRoleIcon = (role: string) => {
    switch (role) {
      case 'LEADER':
        return <Crown className="h-4 w-4" />
      case 'MANAGER':
        return <Star className="h-4 w-4" />
      default:
        return <UserIcon className="h-4 w-4" />
    }
  }

  const handleCreateMember = async (formData: any) => {
    try {
      const response = await fetch(`/api/projects/${projectId}/team`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          ...formData,
          projectId,
          createdBy: "user-1" // 临时用户ID
        })
      })

      if (response.ok) {
        await fetchTeamMembers()
        setDialogOpen(false)
        setEditingMember(null)
      }
    } catch (error) {
      console.error('Error creating team member:', error)
    }
  }

  const handleUpdateMember = async (formData: any) => {
    if (!editingMember) return

    try {
      const response = await fetch(`/api/projects/${projectId}/team/${editingMember.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData)
      })

      if (response.ok) {
        await fetchTeamMembers()
        setDialogOpen(false)
        setEditingMember(null)
      }
    } catch (error) {
      console.error('Error updating team member:', error)
    }
  }

  const handleDeleteMember = async (memberId: string) => {
    if (!confirm('确定要移除这个团队成员吗？')) return

    try {
      const response = await fetch(`/api/projects/${projectId}/team/${memberId}`, {
        method: 'DELETE'
      })

      if (response.ok) {
        await fetchTeamMembers()
      }
    } catch (error) {
      console.error('Error deleting team member:', error)
    }
  }

  const MemberForm = ({ member, onSubmit }: { member?: TeamMember; onSubmit: (data: any) => void }) => {
    const [formData, setFormData] = useState({
      name: member?.name || "",
      email: member?.email || "",
      phone: member?.phone || "",
      department: member?.department || "",
      position: member?.position || "",
      role: member?.role || "MEMBER",
      joinDate: member?.joinDate || "",
      leaveDate: member?.leaveDate || "",
      status: member?.status || "ACTIVE",
      responsibilities: member?.responsibilities || "",
      skills: member?.skills || []
    })

    const [skillInput, setSkillInput] = useState("")

    const handleSubmit = (e: React.FormEvent) => {
      e.preventDefault()
      onSubmit(formData)
    }

    const addSkill = () => {
      if (skillInput.trim() && !formData.skills.includes(skillInput.trim())) {
        setFormData(prev => ({
          ...prev,
          skills: [...prev.skills, skillInput.trim()]
        }))
        setSkillInput("")
      }
    }

    const removeSkill = (skill: string) => {
      setFormData(prev => ({
        ...prev,
        skills: prev.skills.filter(s => s !== skill)
      }))
    }

    return (
      <form onSubmit={handleSubmit} className="space-y-4">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div className="space-y-2">
            <Label htmlFor="name">姓名 *</Label>
            <Input
              id="name"
              value={formData.name}
              onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
              placeholder="输入姓名"
              required
            />
          </div>
          
          <div className="space-y-2">
            <Label htmlFor="email">邮箱 *</Label>
            <Input
              id="email"
              type="email"
              value={formData.email}
              onChange={(e) => setFormData(prev => ({ ...prev, email: e.target.value }))}
              placeholder="输入邮箱地址"
              required
            />
          </div>
          
          <div className="space-y-2">
            <Label htmlFor="phone">电话</Label>
            <Input
              id="phone"
              value={formData.phone}
              onChange={(e) => setFormData(prev => ({ ...prev, phone: e.target.value }))}
              placeholder="输入电话号码"
            />
          </div>
          
          <div className="space-y-2">
            <Label htmlFor="department">部门</Label>
            <Input
              id="department"
              value={formData.department}
              onChange={(e) => setFormData(prev => ({ ...prev, department: e.target.value }))}
              placeholder="输入部门名称"
            />
          </div>
          
          <div className="space-y-2">
            <Label htmlFor="position">职位</Label>
            <Input
              id="position"
              value={formData.position}
              onChange={(e) => setFormData(prev => ({ ...prev, position: e.target.value }))}
              placeholder="输入职位"
            />
          </div>
          
          <div className="space-y-2">
            <Label htmlFor="role">角色</Label>
            <Select value={formData.role} onValueChange={(value) => setFormData(prev => ({ ...prev, role: value }))}>
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="LEADER">项目负责人</SelectItem>
                <SelectItem value="MANAGER">项目经理</SelectItem>
                <SelectItem value="MEMBER">团队成员</SelectItem>
                <SelectItem value="CONTRIBUTOR">贡献者</SelectItem>
              </SelectContent>
            </Select>
          </div>
          
          <div className="space-y-2">
            <Label htmlFor="status">状态</Label>
            <Select value={formData.status} onValueChange={(value) => setFormData(prev => ({ ...prev, status: value }))}>
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="ACTIVE">活跃</SelectItem>
                <SelectItem value="INACTIVE">不活跃</SelectItem>
                <SelectItem value="PENDING">待确认</SelectItem>
                <SelectItem value="LEFT">已离开</SelectItem>
              </SelectContent>
            </Select>
          </div>
          
          <div className="space-y-2">
            <Label htmlFor="joinDate">加入日期</Label>
            <Input
              id="joinDate"
              type="date"
              value={formData.joinDate}
              onChange={(e) => setFormData(prev => ({ ...prev, joinDate: e.target.value }))}
            />
          </div>
          
          <div className="space-y-2">
            <Label htmlFor="leaveDate">离开日期</Label>
            <Input
              id="leaveDate"
              type="date"
              value={formData.leaveDate}
              onChange={(e) => setFormData(prev => ({ ...prev, leaveDate: e.target.value }))}
            />
          </div>
        </div>
        
        <div className="space-y-2">
          <Label htmlFor="responsibilities">职责描述</Label>
          <textarea
            id="responsibilities"
            value={formData.responsibilities}
            onChange={(e) => setFormData(prev => ({ ...prev, responsibilities: e.target.value }))}
            placeholder="输入职责描述"
            rows={3}
            className="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
        </div>
        
        <div className="space-y-2">
          <Label>技能标签</Label>
          <div className="flex gap-2">
            <Input
              value={skillInput}
              onChange={(e) => setSkillInput(e.target.value)}
              placeholder="输入技能标签"
              onKeyPress={(e) => {
                if (e.key === 'Enter') {
                  e.preventDefault()
                  addSkill()
                }
              }}
            />
            <Button type="button" onClick={addSkill} variant="outline">
              添加
            </Button>
          </div>
          <div className="flex flex-wrap gap-2 mt-2">
            {formData.skills.map((skill, index) => (
              <Badge key={index} variant="secondary" className="cursor-pointer" onClick={() => removeSkill(skill)}>
                {skill}
                <span className="ml-1 text-xs">×</span>
              </Badge>
            ))}
          </div>
        </div>
        
        <DialogFooter>
          <Button type="button" variant="outline" onClick={() => setDialogOpen(false)}>
            取消
          </Button>
          <Button type="submit">
            {member ? "更新成员" : "添加成员"}
          </Button>
        </DialogFooter>
      </form>
    )
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div>
          <p className="mt-2 text-sm text-gray-500">加载中...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* 顶部工具栏 */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-xl font-semibold">团队成员管理</h2>
          <p className="text-gray-500">项目: {projectName}</p>
        </div>
        <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
          <DialogTrigger asChild>
            <Button onClick={() => setEditingMember(null)}>
              <Plus className="mr-2 h-4 w-4" />
              添加成员
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>
                {editingMember ? "编辑团队成员" : "添加新成员"}
              </DialogTitle>
              <DialogDescription>
                填写成员信息，{editingMember ? "更新" : "添加"}团队成员记录。
              </DialogDescription>
            </DialogHeader>
            <MemberForm
              member={editingMember}
              onSubmit={editingMember ? handleUpdateMember : handleCreateMember}
            />
          </DialogContent>
        </Dialog>
      </div>

      {/* 统计信息 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-500">总成员数</p>
                <p className="text-2xl font-bold">{teamMembers.length}</p>
              </div>
              <Users className="h-8 w-8 text-blue-600" />
            </div>
          </CardContent>
        </Card>
        
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-500">活跃成员</p>
                <p className="text-2xl font-bold">{teamMembers.filter(m => m.status === 'ACTIVE').length}</p>
              </div>
              <CheckCircle className="h-8 w-8 text-green-600" />
            </div>
          </CardContent>
        </Card>
        
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-500">项目负责人</p>
                <p className="text-2xl font-bold">{teamMembers.filter(m => m.role === 'LEADER').length}</p>
              </div>
              <Crown className="h-8 w-8 text-purple-600" />
            </div>
          </CardContent>
        </Card>
        
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-500">项目经理</p>
                <p className="text-2xl font-bold">{teamMembers.filter(m => m.role === 'MANAGER').length}</p>
              </div>
              <Star className="h-8 w-8 text-blue-600" />
            </div>
          </CardContent>
        </Card>
      </div>

      {/* 团队成员列表 */}
      <Card>
        <CardHeader>
          <CardTitle>团队成员列表</CardTitle>
        </CardHeader>
        <CardContent>
          {teamMembers.length > 0 ? (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>成员信息</TableHead>
                  <TableHead>部门/职位</TableHead>
                  <TableHead>角色</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>加入日期</TableHead>
                  <TableHead>技能</TableHead>
                  <TableHead>操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {teamMembers.map((member) => (
                  <TableRow key={member.id}>
                    <TableCell>
                      <div className="flex items-center gap-3">
                        <div className="h-10 w-10 rounded-full bg-gray-200 flex items-center justify-center">
                          <UserIcon className="h-5 w-5 text-gray-600" />
                        </div>
                        <div>
                          <div className="font-medium">{member.name}</div>
                          <div className="text-sm text-gray-500 flex items-center gap-1">
                            <Mail className="h-3 w-3" />
                            {member.email}
                          </div>
                          {member.phone && (
                            <div className="text-sm text-gray-500 flex items-center gap-1">
                              <Phone className="h-3 w-3" />
                              {member.phone}
                            </div>
                          )}
                        </div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div>
                        <div className="font-medium">{member.position}</div>
                        {member.department && (
                          <div className="text-sm text-gray-500 flex items-center gap-1">
                            <Building className="h-3 w-3" />
                            {member.department}
                          </div>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge className={getRoleColor(member.role)}>
                        <div className="flex items-center gap-1">
                          {getRoleIcon(member.role)}
                          {member.role}
                        </div>
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <Badge className={getStatusColor(member.status)}>
                        {member.status}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center gap-2">
                        <Calendar className="h-4 w-4 text-gray-400" />
                        <span>{member.joinDate ? new Date(member.joinDate).toLocaleDateString() : '-'}</span>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex flex-wrap gap-1">
                        {member.skills.slice(0, 3).map((skill, index) => (
                          <Badge key={index} variant="outline" className="text-xs">
                            {skill}
                          </Badge>
                        ))}
                        {member.skills.length > 3 && (
                          <Badge variant="outline" className="text-xs">
                            +{member.skills.length - 3}
                          </Badge>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center gap-2">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => {
                            setEditingMember(member)
                            setDialogOpen(true)
                          }}
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                        
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleDeleteMember(member.id)}
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          ) : (
            <div className="text-center py-12">
              <Users className="h-12 w-12 text-gray-400 mx-auto mb-4" />
              <h3 className="text-lg font-medium text-gray-900 mb-2">暂无团队成员</h3>
              <p className="text-gray-500 mb-4">开始添加团队成员来协作完成项目</p>
              <Button onClick={() => setDialogOpen(true)}>
                <Plus className="mr-2 h-4 w-4" />
                添加第一个成员
              </Button>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  )
}